package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReprotService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFAnchor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 32338
 * @date 2024-04-30 13:10:43
 * @description 统计
 */
@Service
@Slf4j
public class ReprotServiceImpl implements ReprotService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;


    /**
     * @description
     ***:营业额统计
     **/
    public TurnoverReportVO getTurnoverStatistic(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();//用集合来装日期区间的每一个日期
        dateList.add(begin);
        while (!begin.equals(end)){//当begin等于end的时候停止添加
            begin = begin.plusDays(1);
            dateList.add(begin);//日期计算
        }

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
        //select sum(amount) from orders where order_time>begin and order_time<end and status=5
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);//订单状态为5已完成的订单总金额

           Double turnover = orderMapper.sumByMap(map);

           //判空
           turnover= turnover==null? 0.0:turnover;

           turnoverList.add(turnover);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * @description
     ***:用户统计
     **/
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();//用集合来装日期区间的每一个日期
        dateList.add(begin);
        while (!begin.equals(end)){//当begin等于end的时候停止添加
            begin = begin.plusDays(1);
            dateList.add(begin);//日期计算
        }

        //每天新增的用户数量
        List<Integer> newUserList = new ArrayList<>();
//select count(id) from user where create_time>begin and create_time<end

        // 每天总的用户数量
        List<Integer> totalUserList = new ArrayList<>();
//select count(id) from user where create_time <end

        for (LocalDate date : dateList) {
            //select sum(amount) from orders where order_time>begin and order_time<end and status=5
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("end",endTime);
            Integer userNumber = userMapper.countByMap(map);
            //判空
            userNumber = userNumber == null ? 0 : userNumber;
            totalUserList.add(userNumber);//从当天往后总的用户量


            map.put("begin",beginTime);

            Integer userNumber1 = userMapper.countByMap(map);
            //判空
            userNumber1 = userNumber1 == null ? 0 : userNumber1;

            newUserList.add(userNumber1);

        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * @description
     ***:统计指定时间内的订单数据
     **/
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();//用集合来装日期区间的每一个日期
        dateList.add(begin);
        while (!begin.equals(end)){//当begin等于end的时候停止添加
            begin = begin.plusDays(1);
            dateList.add(begin);//日期计算
        }
        List<Integer> validOrderCountList = new ArrayList<>();//每日有效订单数，以逗号分隔，例如：20,21,10
        List<Integer> orderCountList = new ArrayList<>();//每日订单数，以逗号分隔，例如：260,210,215

        for (LocalDate date : dateList) {
            //select sum(amount) from orders where order_time>begin and order_time<end and status=5
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天的定单总数
            //select count(id) from orders where order_time > begin and order_time < end
            Map map = new HashMap();
            map.put("end",endTime);
            map.put("begin",beginTime);
            Integer orderCount = orderMapper.countByMap(map);
            //判空
            orderCount = orderCount==null ? 0 : orderCount;
            orderCountList.add(orderCount);

            //查询每天有效的订单数
            //select count(id) from orders where order_time > begin and order_time < end and status = 5已完成
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map);
            //判空
            validOrderCount = validOrderCount == null? 0 : validOrderCount;
            validOrderCountList.add(validOrderCount);
        }

        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        log.info("订单总数：{}",totalOrderCount);
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        log.info("有效订单数：{}",validOrderCount);

        //计算完单率
        Double orderCompletionRate =0.0;
        if (totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue()/totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * @description
     ***:销量排名前十的菜品
     **/
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        //查询语句 select od.name,sum(od.number) number from order_detail od ,orders o
        // where od.order_id = o.id and status = 5 and o.order_time > begin and o.order_time < end
        //group by od.name
        //order by number desc
        //limit 0,10
        /*获得时间区间*/
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * @description
     ***:导出运营数据报表
     **/
    public void exportBusinessDate(HttpServletResponse response) {
        //查询数据库，获取营业数据
        LocalDate beginTime = LocalDate.now().minusDays(30);
        LocalDate endTime = LocalDate.now().minusDays(1);

        BusinessDataVO businessVO = workspaceService.getBusinessData(
                LocalDateTime.of(beginTime, LocalTime.MIN),
                LocalDateTime.of(endTime, LocalTime.MAX));

        //写入到excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //填充数据 -- 概览数据
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            sheet1.getRow(1).getCell(1).setCellValue("时间："+beginTime+" 至 "+endTime);//设置时间区域
            XSSFRow row = sheet1.getRow(3);
            row.getCell(2).setCellValue(businessVO.getTurnover());//设置营业额
            row.getCell(4).setCellValue(businessVO.getOrderCompletionRate());//订单完成率
            row.getCell(6).setCellValue(businessVO.getNewUsers());//新增用户数

            row = sheet1.getRow(4);
            row.getCell(2).setCellValue(businessVO.getValidOrderCount());//有效订单
            row.getCell(4).setCellValue(businessVO.getUnitPrice());//平均客单价

            //填充数据 -- 明细数据
            for (int i = 0;i<30;i++){
                LocalDate date = beginTime.plusDays(i);

                BusinessDataVO businessData = workspaceService.getBusinessData(
                        LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));//获得当天的营业数据

                row = sheet1.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());

            }


            //通过输出流下载到浏览器
            ServletOutputStream ot = response.getOutputStream();
            excel.write(ot);

            //关闭资源
            excel.close();
            ot.close();
        } catch (Exception e) {
            e.printStackTrace();
        }



    }
}
